import axios from "axios"
import AskEditIcon from "data-base64:~assets/icon_search_ai.svg"
import type { PlasmoCSConfig } from "plasmo"
import { useEffect, useRef, useState } from "react"

export const config: PlasmoCSConfig = {
  matches: ["<all_urls>"]
}

export default function Base() {
  const [selectedText, setSelectedText] = useState("")
  const [showTool, setShowTool] = useState(false)
  const [coordinate, setCoordinate] = useState({ x: -999, y: -999 })

  const divRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    document.body.addEventListener("mouseup", () => {
      setTimeout(() => checkSelection())
    })
    document.body.addEventListener("mousedown", () => {
      setShowTool(false)
    })
    chrome.runtime.onMessage.addListener((message) => {
      console.log("我是content,我接收了")
      console.log(message, "message")
      if (message.type === "SSOLogin") {
        SSOLogin({ currentUrl: location.href })
      }
    })
    getQuery()
  }, [])
  function getQuery() {
    const urlData = new URL(location.href).search
    let h3c_ticket = ""
    if (urlData.includes("h3c_ticket")) {
      h3c_ticket = urlData.split("=")[1]
      SSOLogin({ h3cTicket: h3c_ticket })
    }
  }

  async function SSOLogin(data) {
    axios
      .post("https://api-ai-ts.h3c.com/assistant/api/user/login", data, {
        data: {},
        headers: {
          "Auth-Type": "SSO_NEXT"
        }
      })
      .then((response) => {
        chrome.runtime.sendMessage({
          type: "loginSuccess",
          data: {
            token: "123"
          }
        })

        const { ssoLoginUrl: url, ssoLogoutUrl: redirectUrl } =
          response.data.data

        if (url) {
          location.href = url
        }
      })
  }

  async function click() {
    chrome.runtime.sendMessage({
      type: "selectText",
      data: selectedText
    })
  }
  function checkSelection() {
    const selection = window.getSelection()
    const selectionText = selection?.toString().trim()

    if (!selection?.isCollapsed && selectionText && selectionText.trim()) {
      setSelectedText(selectionText)
      const range = selection?.getRangeAt(0)

      const rect = range?.getBoundingClientRect()

      let x = (rect?.left ?? 0) + window.scrollX

      let toolTipWidth = 280

      if (divRef.current) {
        toolTipWidth = divRef.current.offsetWidth
      }

      if (x + toolTipWidth > window.innerWidth) {
        x = window.innerWidth - toolTipWidth - 10
      }
      setCoordinate({
        x: x,
        y: (rect?.bottom ?? 0) + window.scrollY + 10
      })
      setShowTool(true)
    } else {
    }
  }

  function analysis() {
    const text = document.body.innerText
    chrome.runtime.sendMessage({
      type: "allHtml",
      data: text
    })
  }
  return (
    <span>
      <div
        style={{
          position: "fixed",
          padding: "10px",
          background: "#fff",
          right: 0,
          top: 0,
          fontSize: "12px"
        }}
        onClick={analysis}>
        解析网页
      </div>
      <div
        style={{
          position: "fixed",
          width: "40px",
          boxShadow: "0 0 0 0 #0000,0 0 0 0 #0000, 0 4px 12px 0px #0003",
          left: `${coordinate.x}px`,
          top: `${coordinate.y}px`,
          display: showTool ? "block" : "none",
          background: "#fff"
        }}>
        <img
          onClick={click}
          className={
            "ml-[8px] inline-block align-text-bottom w-[16px] h-[16px]"
          }
          src={AskEditIcon}
          alt=""
        />
      </div>
    </span>
  )
}
